<template>
  <div class="app-container" :class="{ 'dark-mode': isDarkMode }">
    <!-- 顶部导航栏 -->
    <div class="app-header">
      <div class="app-title">
        <el-icon><ChatDotRound /></el-icon>
        <h1>Devil 助手</h1>
      </div>
      <div class="header-actions">
        <!-- 主题切换按钮 -->
        <el-tooltip :content="isDarkMode ? '切换到亮色模式' : '切换到暗色模式'" placement="bottom">
          <el-button circle @click="toggleDarkMode">
            <el-icon v-if="isDarkMode"><Sunny /></el-icon>
            <el-icon v-else><Moon /></el-icon>
          </el-button>
        </el-tooltip>
        <!-- 清空聊天按钮 -->
        <el-tooltip content="清空聊天" placement="bottom">
          <el-button circle @click="clearChat">
            <el-icon><Delete /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <div class="main-content">
      <!-- 侧边栏 -->
      <div class="sidebar" :class="{ 'sidebar-collapsed': isSidebarCollapsed }">
        <div class="sidebar-header">
          <h3>历史会话</h3>
          <el-button circle size="small" @click="toggleSidebar">
            <el-icon v-if="isSidebarCollapsed"><ArrowRight /></el-icon>
            <el-icon v-else><ArrowLeft /></el-icon>
          </el-button>
        </div>
        <div v-if="!isSidebarCollapsed" class="sidebar-content">
          <div class="history-item" @click="startNewChat">
            <el-icon><Plus /></el-icon>
            <span>新对话</span>
          </div>
          <!-- 这里可以添加历史会话列表 -->
          <div class="history-placeholder">暂无历史会话</div>
        </div>
      </div>

      <!-- 聊天主体部分 -->
      <div class="chat-container">
        <div class="chat-body">
          <div class="messages-container" ref="messagesContainer">
            <el-timeline>
              <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :icon="activity.icon"
                  :type="activity.type"
                  :color="activity.color"
                  :size="activity.size"
                  :hollow="activity.hollow"
                  :timestamp="activity.timestamp"
                  :class="['timeline-item', activity.role]"
              >
                <div class="message-content markdown-body" v-html="renderMarkdown(activity.content)"></div>
              </el-timeline-item>
            </el-timeline>
          </div>

          <div class="chat-input-container">
            <el-input
                v-model="msg"
                class="chat-input"
                type="textarea"
                :rows="2"
                :autosize="{ minRows: 1, maxRows: 4 }"
                placeholder="请输入您的问题..."
                @keydown.enter.prevent="sendMsg"
            />
            <el-button
                type="primary"
                class="send-button"
                @click="sendMsg"
                :loading="isLoading"
                :disabled="!msg.trim()"
            >
              <el-icon v-if="!isLoading"><Position /></el-icon>
              <span>{{ isLoading ? '发送中...' : '发送' }}</span>
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  ArrowLeft,
  ArrowRight,
  ChatDotRound,
  Delete,
  Moon,
  MoreFilled,
  Plus,
  Position,
  Sunny
} from '@element-plus/icons-vue'
import {nextTick, onMounted, ref} from "vue";
// 引入markdown-it和highlight.js
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css'; // 导入代码高亮样式

export default {
  components: {
    Position,
    ChatDotRound,
    Sunny,
    Moon,
    Delete,
    ArrowLeft,
    ArrowRight,
    Plus
  },
  data() {
    return {
      span: 15,
      span1: 8,
      drawer: true,
      // 初始化markdown-it实例
      md: new MarkdownIt({
        html: true,
        linkify: true,
        typographer: true,
        highlight: function (str, lang) {
          if (lang && hljs.getLanguage(lang)) {
            try {
              return hljs.highlight(str, { language: lang }).value;
            } catch (__) {}
          }
          return ''; // 使用默认的转义
        }
      })
    };
  },
  methods: {
    clickImg() {
      this.drawer = !this.drawer;
      if (this.drawer) {
        this.span = 15;
        this.span1 = 8;
      } else {
        this.span = 1;
        this.span1 = 23;
      }
    },
    // 替换formatContent方法为renderMarkdown方法
    renderMarkdown(content) {
      if (typeof content === 'string') {
        // 检查是否包含typing-indicator，如果包含则直接返回
        if (content.includes('typing-indicator')) {
          return content;
        }
        // 渲染Markdown内容
        return this.md.render(content);
      }
      return content;
    }
  },
  setup() {
    const activities = ref([
      {
        content: '⭐ 欢迎使用 Devil 助手！请问有什么可以帮您的?',
        timestamp: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
        color: '#0bbd87',
        role: 'assistant' // 添加角色标识
      },
    ]);
    const msg = ref('');
    const tableData = ref([]);
    const isLoading = ref(false);
    const messagesContainer = ref(null);
    const isDarkMode = ref(false);
    const isSidebarCollapsed = ref(true);
    let count = 1;
    let eventSource;

    // 切换暗黑模式
    const toggleDarkMode = () => {
      isDarkMode.value = !isDarkMode.value;
      // 可以在这里保存用户偏好到localStorage
      localStorage.setItem('devil-dark-mode', isDarkMode.value ? 'true' : 'false');
    };

    // 切换侧边栏
    const toggleSidebar = () => {
      isSidebarCollapsed.value = !isSidebarCollapsed.value;
    };

    // 清空聊天
    const clearChat = () => {
      activities.value = [
        {
          content: '⭐ 聊天已清空，有什么可以帮您的?',
          timestamp: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
          color: '#0bbd87',
          role: 'assistant'
        },
      ];
    };

    // 开始新对话
    const startNewChat = () => {
      clearChat();
    };

    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
        }
      });
    };

    const sendMsg = () => {
      if (!msg.value.trim() || isLoading.value) return;

      isLoading.value = true;

      if (eventSource) {
        eventSource.close();
      }

      activities.value.push(
          {
            content: msg.value,
            timestamp: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
            size: 'large',
            type: 'primary',
            icon: MoreFilled,
            class: 'user-message',
            role: 'user' // 添加用户角色标识
          },
      );

      count = activities.value.length;

      activities.value.push(
          {
            content: '<span class="typing-indicator"><span>.</span><span>.</span><span>.</span></span>',
            timestamp: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
            color: '#0bbd87',
            role: 'assistant' // 添加助手角色标识
          },
      );

      scrollToBottom();

      // sse: 服务端推送 Server-Sent Events
      eventSource = new EventSource(`http://localhost:8080/assistant/chat?message=${encodeURIComponent(msg.value)}`);
      const savedMsg = msg.value;
      msg.value = '';

      eventSource.onmessage = (event) => {
        if (event.data === '[complete]') {
          isLoading.value = false;
          eventSource.close();
          scrollToBottom();
          return;
        }

        if (activities.value[count].content.includes('typing-indicator')) {
          activities.value[count].content = event.data;
        } else {
          activities.value[count].content += event.data;
        }

        scrollToBottom();
      };

      eventSource.onopen = () => {
        activities.value[count].content = '';
      };

      eventSource.onerror = () => {
        if (activities.value[count].content === '') {
          activities.value[count].content = '抱歉，服务连接出现问题，请稍后再试。';
        }
        isLoading.value = false;
        eventSource.close();
        scrollToBottom();
      };
    };

    onMounted(() => {
      scrollToBottom();
      // 从localStorage加载暗黑模式设置
      const savedDarkMode = localStorage.getItem('devil-dark-mode');
      if (savedDarkMode === 'true') {
        isDarkMode.value = true;
      }
    });

    return {
      activities,
      msg,
      tableData,
      sendMsg,
      isLoading,
      messagesContainer,
      isDarkMode,
      toggleDarkMode,
      isSidebarCollapsed,
      toggleSidebar,
      clearChat,
      startNewChat
    };
  },
};
</script>

<style scoped>
/* 应用容器样式 */
.app-container {
  display: flex;
  flex-direction: column;
  height: 80vh;
  background-color: #f5f7fa;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  transition: background-color 0.3s, color 0.3s;
}

/* 暗黑模式样式 */
.dark-mode {
  background-color: #1a1a1a;
  color: #f0f0f0;
}

.dark-mode :deep(.el-timeline-item__content) {
  color: #f0f0f0;
}

.dark-mode :deep(.timeline-item.user .message-content) {
  background-color: #2d3748;
  color: #f0f0f0;
}

.dark-mode :deep(.timeline-item.user .message-content::after) {
  border-left-color: #2d3748;
}

.dark-mode :deep(.timeline-item.assistant .message-content) {
  background-color: #2c2c2c;
  color: #f0f0f0;
}

.dark-mode :deep(.timeline-item.assistant .message-content::after) {
  border-right-color: #2c2c2c;
}

.dark-mode .chat-input-container {
  background-color: #2c2c2c;
  border-top: 1px solid #444;
}

.dark-mode :deep(.chat-input .el-textarea__inner) {
  background-color: #333;
  border-color: #555;
  color: #f0f0f0;
}

.dark-mode :deep(.chat-input .el-textarea__inner::placeholder) {
  color: #aaa;
}

.dark-mode .app-header {
  background-color: #2c2c2c;
  border-bottom: 1px solid #444;
}

.dark-mode .sidebar {
  background-color: #2c2c2c;
  border-right: 1px solid #444;
}

.dark-mode .sidebar-header {
  border-bottom: 1px solid #444;
}

.dark-mode .history-item:hover {
  background-color: #3a3a3a;
}

/* 顶部导航栏样式 */
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.app-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.app-title h1 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 主内容区域样式 */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
  border: 1px solid #eaeaea;
}

/* 侧边栏样式 */
.sidebar {
  width: 250px;
  background-color: white;
  border-right: 1px solid #eaeaea;
  transition: width 0.3s;
  display: flex;
  flex-direction: column;
}

.sidebar-collapsed {
  width: 50px;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eaeaea;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 1rem;
}

.sidebar-content {
  padding: 15px;
  overflow-y: auto;
  flex: 1;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.history-item:hover {
  background-color: #f0f0f0;
}

.history-placeholder {
  text-align: center;
  color: #999;
  margin-top: 20px;
  font-style: italic;
}

/* 聊天容器样式 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(80vh - 80px);
  background-color: transparent;
  position: relative;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin: 10px;
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(234, 234, 234, 0.8);
  overflow: hidden;
}

.dark-mode .chat-container {
  background-color: rgba(40, 40, 40, 0.7);
  border: 1px solid rgba(60, 60, 60, 0.8);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.messages-container {
  max-height: 70vh;
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scrollbar-width: thin;
  scrollbar-color: #d4d4d4 transparent;
}

/* 添加滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background-color: #d4d4d4;
  border-radius: 6px;
}

.dark-mode .messages-container::-webkit-scrollbar-thumb {
  background-color: #555;
}

/* 修改时间线项目样式，使用户和助手消息分别靠右和靠左显示 */
:deep(.el-timeline-item) {
  position: relative;
  width: 100%;
  margin-bottom: 12px; /* 进一步减小消息之间的间距 */
}

/* 用户消息靠右显示 */
:deep(.timeline-item.user) {
  text-align: right;
}

:deep(.timeline-item.user .el-timeline-item__content) {
  margin-left: auto;
  margin-right: 25px;
  max-width: 70%;
  display: inline-block;
  width: auto;
}

/* 助手消息靠左显示 */
:deep(.timeline-item.assistant) {
  text-align: left;
}

:deep(.timeline-item.assistant .el-timeline-item__content) {
  margin-left: 25px;
  margin-right: auto;
  max-width: 70%;
  display: inline-block;
  width: auto;
}

/* 修改消息气泡样式 */
:deep(.message-content) {
  padding: 6px 10px; /* 进一步减小内边距 */
  border-radius: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  margin-top: 3px; /* 减小顶部边距 */
  position: relative;
  display: inline-block;
  max-width: 100%;
  word-wrap: break-word;
}

:deep(.timeline-item.user .message-content) {
  background-color: #e3f2fd;
  border-top-right-radius: 4px;
  text-align: left;
  color: #333;
}

:deep(.timeline-item.assistant .message-content) {
  background-color: white;
  border-top-left-radius: 4px;
  text-align: left;
  color: #333;
}

/* 美化时间戳 */
:deep(.el-timeline-item__timestamp) {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  opacity: 0.8;
}

:deep(.timeline-item.user .el-timeline-item__timestamp) {
  text-align: right;
  padding-right: 25px;
}

:deep(.timeline-item.assistant .el-timeline-item__timestamp) {
  text-align: left;
  padding-left: 25px;
}

/* 添加消息尾巴效果 */
:deep(.timeline-item.user .message-content::after) {
  content: '';
  position: absolute;
  top: 0;
  right: -10px;
  width: 0;
  height: 0;
  border: 10px solid transparent;
  border-left-color: #e3f2fd;
  border-right: 0;
  border-top: 0;
  margin-right: 0;
}

:deep(.timeline-item.assistant .message-content::after) {
  content: '';
  position: absolute;
  top: 0;
  left: -10px;
  width: 0;
  height: 0;
  border: 10px solid transparent;
  border-right-color: white;
  border-left: 0;
  border-top: 0;
  margin-left: 0;
}

/* 添加打字指示器动画 */
:deep(.typing-indicator) {
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
}

:deep(.typing-indicator span) {
  height: 8px;
  width: 8px;
  margin: 0 2px;
  background-color: #606266;
  display: block;
  border-radius: 50%;
  opacity: 0.4;
  animation: typing 1s infinite ease-in-out;
}

:deep(.typing-indicator span:nth-child(1)) {
  animation-delay: 0s;
}

:deep(.typing-indicator span:nth-child(2)) {
  animation-delay: 0.2s;
}

:deep(.typing-indicator span:nth-child(3)) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0% {
    transform: translateY(0px);
    opacity: 0.4;
  }
  50% {
    transform: translateY(-5px);
    opacity: 0.8;
  }
  100% {
    transform: translateY(0px);
    opacity: 0.4;
  }
}

/* 添加Markdown样式 */
:deep(.markdown-body) {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
  line-height: 1.3; /* 进一步减小行高 */
  font-size: 13px; /* 进一步减小字体大小 */
}

/* 减小Markdown元素的边距 */
:deep(.markdown-body p) {
  margin-top: 0.3em;
  margin-bottom: 0.3em;
}

:deep(.markdown-body h1) {
  font-size: 1.4em;
  margin-top: 0.4em;
  margin-bottom: 0.4em;
}

:deep(.markdown-body h2) {
  font-size: 1.2em;
  margin-top: 0.4em;
  margin-bottom: 0.4em;
}

:deep(.markdown-body h3) {
  font-size: 1.1em;
  margin-top: 0.3em;
  margin-bottom: 0.3em;
}

:deep(.markdown-body pre) {
  padding: 8px;
  margin-bottom: 12px;
}

:deep(.markdown-body ul, .markdown-body ol) {
  padding-left: 1.5em;
  margin-top: 0;
  margin-bottom: 12px;
}

:deep(.markdown-body table) {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 16px;
}

:deep(.markdown-body table th, .markdown-body table td) {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

:deep(.markdown-body table tr:nth-child(2n)) {
  background-color: #f6f8fa;
}

:deep(.markdown-body img) {
  max-width: 100%;
  box-sizing: border-box;
}


/* 输入框固定在底部 - 修改样式 */
.chat-input-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 16px 20px;
  background-color: white;
  border-top: 1px solid #eaeaea;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  gap: 12px;
  align-items: flex-end;
  z-index: 10;
  border-radius: 0 0 8px 8px;
}

/* 添加输入框样式 */
:deep(.chat-input .el-textarea__inner) {
  border-radius: 18px;
  padding: 10px 15px;
  resize: none;
  transition: all 0.3s;
  border: 1px solid #dcdfe6;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.03);
}

:deep(.chat-input .el-textarea__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 发送按钮样式 */
.send-button {
  border-radius: 50%;
  min-width: 44px;
  height: 44px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  margin-bottom: 2px;
}

.send-button:not(:disabled):hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 隐藏发送按钮文本，只显示图标 */
.send-button span:not(.el-icon) {
  display: none;
}

.send-button .el-icon {
  font-size: 20px;
}

/* 当输入框获得焦点时的样式 */
:deep(.chat-input:focus-within .el-textarea__inner) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 占位符文本样式 */
:deep(.chat-input .el-textarea__inner::placeholder) {
  color: #a0a0a0;
  font-style: italic;
}

/* 调整消息容器的底部边距，为输入框留出空间 */
.messages-container {
  padding-bottom: 80px;
}
</style>
